<%@page import="com.xcalendar.database.table.User"%>
<%@page import="com.xcalendar.constant.XConstants"%>
<%@page import="com.xcalendar.database.table.Event"%>
<%@page import="java.util.List"%>
<%@page import="java.util.HashMap"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.Map"%>
<%@page import="org.json.JSONException"%>
<%@page import="org.json.JSONObject"%>
<%@page import="org.json.JSONArray"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%
	Map<String, String> valueMap = new HashMap<String, String>();
	User user = (User) request.getSession().getAttribute(XConstants.SESSION_USER);
	String eventString = "";
	if (request.getSession().getAttribute(XConstants.ISLOGGED).equals("true")) {

		eventString = (String) request.getSession().getAttribute(XConstants.JSONEVENTS);
	} else {
%><jsp:forward page="welcome.jsp" />
<%
	}
	String defaultView = (String)request.getSession().getAttribute(XConstants.DEFAULTVIEW);
	if(defaultView==null){
		defaultView = request.getParameter("view");
		if(defaultView==null){
			defaultView = "month";
		}
	}

	
	String locationString = "";
	locationString = (String) request.getSession().getAttribute(XConstants.JSONLOCATIONS);
	System.out.print(locationString);
%>



<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>XCalendarHomePage</title>
<link rel='stylesheet' type='text/css' href='../fullcalendar/fullcalendar.css' />
<link rel='stylesheet' type='text/css' href='../fullcalendar/fullcalendar.print.css' media='print' />
<link rel='stylesheet' type='text/css' href='../css/ui-lightness/jquery-ui-1.8.16.custom.css' />
<script type='text/javascript' src='../jquery/jquery-1.6.2.min.js'></script>
<script type='text/javascript' src='../jquery/jquery-ui-1.8.16.custom.min.js'></script>
<script type='text/javascript' src='../fullcalendar/fullcalendar.min.js'></script>
<script>
	$(function() {
		$( "input:submit, a, button" ).button();
	});
</script>

<script type="text/javascript">


</script>
<script type='text/javascript'>
var month=new Array(12);
month[0]="01";
month[1]="02";
month[2]="03";
month[3]="04";
month[4]="05";
month[5]="06";
month[6]="07";
month[7]="08";
month[8]="09";
month[9]="10";
month[10]="11";
month[11]="12";
$(document).ready(function() {
	
	$(document).ready(function() {
        createDropDown();
        $(".dropdown").mouseenter(function() {
        	$(".dropdown dd ul").slideDown(80);
          }).mouseleave(function(){
        	$(".dropdown dd ul").slideUp(30);
          });
    });

    function createDropDown(){
           
    	var locations = <%=locationString%>;
           $.each(locations,function(i){
        	   
       	    $("#source").append("<option>"+locations[i].locationName +"</option>")
       	    
       	    });

        var source = $("#source");
        var selected = source.find("option[selected]");
        var options = $("option", source);
        
     
        
       
        $("#logout").after('<td width="205"><dl id="target" class="dropdown"></dl></td>')
        $("#target").append('<dt><a href="#">My Locations' + 
            '<span class="value">' + selected.val() + 
            '</span></a></dt>')
        $("#target").append('<dd><ul></ul></dd>')
        

        
        options.each(function(){
            $("#target dd ul").append('<li><a href="#">' + 
                $(this).text() + '<span class="value">' + 
                $(this).val() + '</span></a></li>');
        });
        
        
    }
	
    
	
	
	var date = new Date();
	var clickEventSDate = new Date();
	var clickEventEDate = new Date();
	var clickEventId;
	var clickEventLocationName;
	var clickEventLocationKey;
	var newEventSDate = new Date();
	var newEventEDate = new Date();
	var d = date.getDate();
	var m = date.getMonth();
	var y = date.getFullYear();
	var newTitle = $( "#newTitle" ),
	newDec = $( "#newDec" );
	var locationKey = $( "#locationKey" );
	var clickEventTitle, clickEventDec;
	var calendar = $('#calendar').fullCalendar({
		defaultView: '<%=defaultView%>',
		theme: true,
		header: {
			left: 'prev,next today',
			center: 'title',
			right: 'month,agendaWeek,agendaDay'
		},
		selectable: true,
		selectHelper: true,
		select: function(start, end, allDay) {
			newEventSDate = start;
			newEventEDate = end;
			
			var sMin;
			var eMin;
			if(start.getMinutes()==0){sMin="00";}else{sMin="30";}
			if(end.getMinutes()==0){eMin="00";}else{eMin="30";}
			document.getElementById("new-start").innerHTML = start.getFullYear()+"/"+month[start.getMonth()]+"/"+start.getDate()+"  "+start.getHours()+":"+sMin;
			document.getElementById("new-end").innerHTML =  end.getFullYear()+"/"+month[end.getMonth()]+"/"+end.getDate()+"  "+end.getHours()+":"+eMin;
			$( "#create-event-dialog-form" ).dialog( "open" );
		},
		editable: true,
		
		events : <%=eventString%>,
		eventClick : function(calEvent, jsEvent, view) {
			clickEventSDate = calEvent.start;
			clickEventEDate = calEvent.end;
			clickEventTitle = calEvent.title;
			clickEventDec = calEvent.description;
			clickEventLocationName = calEvent.locationName;
			clickEventLocationKey = calEvent.locationKey;
			clickEventId = calEvent.id;
			//alert(clickEventId);
			var sDate = calEvent.start;
			var eDate = calEvent.end;
			var sMin;
			var eMin;
			var sDay;
			var eDay;
			if(sDate.getDate()<10){sDay="0"+sDate.getDate();}else{sDay=sDate.getDate();}
			if(eDate.getDate()<10){eDay="0"+eDate.getDate();}else{eDay=eDate.getDate();}
			if(sDate.getMinutes()==0){sMin="00";}else{sMin="30";}
			if(eDate.getMinutes()==0){eMin="00";}else{eMin="30";}
			document.getElementById("start").innerHTML = month[sDate.getMonth()]+"/"+sDay+"/"+sDate.getFullYear()+"  "+sDate.getHours()+":"+sMin;
			document.getElementById("end").innerHTML =  month[eDate.getMonth()]+"/"+eDay+"/"+eDate.getFullYear()+"  "+eDate.getHours()+":"+eMin;
			document.getElementById("title").innerHTML = calEvent.title;
			document.getElementById("description").innerHTML = calEvent.description;
			if(calEvent.locationName!=null){document.getElementById("location").innerHTML = calEvent.locationName;}
			
			document.getElementById("location").innerHTML = calEvent.locationName;
			$( "#click-event-dialog-form" ).dialog( "open" );
		},
		
		eventResize: function(event,dayDelta,minuteDelta,revertFunc) {
				 $.post("/resizeEventController",{eventIdResize:event.id, eventTitleResize:event.title,
					 eventStartResize:event.start.toString(), eventEndResize:event.end.toString(),
					 eventDescriptionResize:event.description}, function(data) {
		            }).complete(function() {						
						alert("Resize event successfully!");
		            });


		    },

		
		   eventDrop: function(event,dayDelta,minuteDelta,allDay,revertFunc) {

			   
			   var dropSuccess = new Boolean("false");
			   
				 $.post("/dragEventController",{eventIdDrop:event.id, eventTitleDrop:event.title,
					 eventStartDrop: event.start.toString(), eventEndDrop:event.end.toString(),
					 eventDescriptionDrop: event.description}, function(data) {
		            }).complete(function() {						
						alert("Drag event successfully!");
		            });
		    }
		
	});
	$( "#click-event-dialog-form" ).dialog({
		autoOpen: false,
		height: 250,
		width: 400,
		modal: true,
		buttons: {
			"Delete": function() {
				$.post("/deleteEventController",{eventId:clickEventId}, function(data) {
					
	            }).complete(function() {
	            	//alert(document.getElementById('locationKey').options[document.getElementById('locationKey').selectedIndex].text);
					calendar.fullCalendar('removeEvents',[ clickEventId ]);
					//calendar.fullCalendar('unselect');					
					alert("Delete event successfully!");
					$( "#click-event-dialog-form" ).dialog( "close" );
	            });
			},
			"Edit": function() {

				editForm.id.value = clickEventId;
				editForm.title.value = clickEventTitle;
				editForm.description.value = clickEventDec;
				editForm.locationKey.value = clickEventLocationKey;
				editForm.locationName.value = clickEventLocationName;
				
				var sMin;
				var eMin;
				var sDay;
				var eDay;
				if(clickEventSDate.getDate()<10){sDay="0"+clickEventSDate.getDate();}else{sDay=clickEventSDate.getDate();}
				if(clickEventEDate.getDate()<10){eDay="0"+clickEventEDate.getDate();}else{eDay=clickEventEDate.getDate();}
				if(clickEventSDate.getMinutes()==0){sMin="00";}else{sMin="30";}
				if(clickEventEDate.getMinutes()==0){eMin="00";}else{eMin="30";}
				editForm.start.value = month[clickEventSDate.getMonth()]+"/"+sDay+"/"+clickEventSDate.getFullYear()+"&nbsp;"+clickEventSDate.getHours()+":"+sMin;
				editForm.end.value = month[clickEventEDate.getMonth()]+"/"+eDay+"/"+clickEventEDate.getFullYear()+"&nbsp;"+clickEventEDate.getHours()+":"+sMin;;
				editForm.view.value = $('#calendar').fullCalendar('getView').name;
				editForm.submit();
				//window.location.href = "editEvent.jsp?title="+clickEventTitle+"&description="+clickEventDec+"&start="+clickEventSDate+"&end="+clickEventEDate+"&id="+clickEventId;
			},
			Cancel: function() {
				$( this ).dialog( "close" );
			}
		},
		close: function() {
			allFields.val( "" ).removeClass( "ui-state-error" );
		}
	});
	$( "#create-event-dialog-form" ).dialog({
		autoOpen: false,
		height: 250,
		width: 400,
		modal: true,
		buttons: {
			"Create": function() {
				
				$.post("/addEventController",{eventTitle:newTitle.val(), eventDescription:newDec.val(), eventStart:newEventSDate.getTime(), eventEnd:newEventEDate.getTime(),locationKey:locationKey.val()}, function(data) {
					idEvent = data;
					//alert(locationKey.innerText);
	            }).complete(function() {
	            	//alert(document.getElementById('locationKey').options[document.getElementById('locationKey').selectedIndex].text);
					calendar.fullCalendar('renderEvent',
							{
								id: idEvent,
								title: newTitle.val(),
								description: newDec.val(),
								start: newEventSDate,
								end: newEventEDate,
								locationKey:locationKey.val(),
								locationName:document.getElementById('locationKey').options[document.getElementById('locationKey').selectedIndex].text,
								allDay: false
							},
							true // make the event "stick"
					);
					calendar.fullCalendar('unselect');					
					alert("Add event successfully!");
					
					$("#newTitle").attr("value",'');
					$("#newDec").attr("value",'');
					$( "#create-event-dialog-form" ).dialog( "close" );
	            });
			},
			Cancel: function() {
				$("#newTitle").attr("value",'');
				$("#newDec").attr("value",'');
				$( this ).dialog( "close" );
			}
		},
		close: function() {			
			allFields.val( "" ).removeClass( "ui-state-error" );
		}
	});
});

</script>
<style type='text/css'>

body {
	margin-top: 50px;
	text-align: center;
	font-size: 14px;
	font-family: "Lucida Grande", Helvetica, Arial, Verdana, sans-serif;
	color: #007FFF;
	background-image:url(../bg/6_6.jpg); 
	background-position: center;
	background-attachment: fixed;
	repeat-x: #FFFFFF
}
        .desc { color:white;}
        .desc a {color:white;}
       	.dropdown { float: right; }
        .dropdown dd, .dropdown dt, .dropdown ul { margin:0px; padding:0px; }
        .dropdown dd { position:relative; }
        .dropdown a { color:white; text-decoration:none; outline:none;}
        .dropdown a:visited { color:white; text-decoration:none; outline:none;}
        .dropdown a:hover {color:#5d4617;}
        .dropdown dt a:hover { color:#ffaa33; border: 1px solid #176FB9;}
        .dropdown dt a {background:#176FB9 url(arrow.png) no-repeat scroll right center; display:block; 
                        border:1px solid #176FB9; width:170px; padding:0px;}
        .dropdown dt a span {cursor:pointer; display:block; }
        .dropdown dd ul {background:#176FB9 none repeat scroll 0 0; border:1px solid #176FB9; color:#ffaa33; display:none;
                          left:0px; padding:5px 0px; position:absolute; top:0px; width:auto; min-width:170px; list-style:none;}
        .dropdown span.value { display:none;}
        .dropdown dd ul li a { padding:1px; display:block;font-size:13px;}
        .dropdown dd ul li a:hover {color:#ffaa33;border:1px solid #176FB9;}
        
        .dropdown img.flag { border:none; vertical-align:middle; margin-left:10px; }
        .flagvisibility { display:none;}
      
	     #float_banner{background-color:#176FB9;
	     				height: 32px;
						width: 100%; 
						float: left; 
						display: block; 
						overflow: visible; 
						position: fixed; 
						top: 0px; /* position fixed for IE6 */ 
						_position: absolute; 
						_top: expression(documentElement.scrollTop + "px");  
						z-index:100;
						
			}
        #source {display:none;}
#calendar {
	width: 900px;
	margin: 0 auto;
}
.helloName {display: inline; }
form{display: inline; float:right;}
table.titleTable{margin-top: 0px;top:0px;margin:0;padding:0;color:white;}

*{margin:0;padding:0;}
.logoutinput{width: 100px;high:25px;font-size:9pt;padding:0px;font-weight:bold;}
#helloN{font-size:10pt;padding:0px;font-family:Arial,Verdana,Sans-serif}


</style>
</head>
<body>

	<div class="titleBar" align="right" id="float_banner">
	<table class="titleTable">
		<tr>
		<td width="900"></td>
		<td id="helloName" width="100">
		<div class="helloName" id="helloN"><nobr>Hello! <%=user.getUserName()%></nobr></div>
		</td>
		<td id="logout" width="85">	
		<form  name="logout" method="post" action="logoutController" >
			<label class="field"><input align="middle" type="submit" value="Logout" class="logoutinput"/>
			</label>
		</form>	
		</td>
		</tr>
		</table>	
	</div>
	
	<div id='calendar'></div>

<div id="click-event-dialog-form" title="Click an event" align="center">
	<table>
	<tr><td>Start : </td><td id="start" ></td></tr>
	<tr><td>End : </td><td id="end" ></td></tr>
	<tr><td>Title : </td><td id="title" ></td></tr>
	<tr><td>Description : </td><td id="description" ></td></tr>
	<tr><td>Location : </td><td id="location" ></td></tr>
	</table>
</div>
<div id="create-event-dialog-form" title="Create an event" align="center">
	<table>
	<tr><td>Start : </td><td id="new-start" ></td></tr>
	<tr><td>End : </td><td id="new-end" ></td></tr>
	<tr>
		<td>Title : </td>
		<td id="title" >
			<input type="text" id="newTitle" class="text ui-widget-content ui-corner-all" />
		</td>
	</tr>
	<tr>
		<td>Description : </td>
		<td id="description" >
			<input type="text" id="newDec" class="text ui-widget-content ui-corner-all" />
		</td>
	</tr>
	<tr>
		<td>Location : </td>
		<td id="location" >
			
			<select id="locationKey" class="text ui-widget-content ui-corner-all">
			<option selected="selected">Select your locations</option>
					<%
				if(locationString != null){
				JSONArray jsonArray = new JSONArray(locationString);
				
				
				for(int j=0;j<jsonArray.length();j++){
					JSONObject jsonObject = jsonArray.getJSONObject(j);
					String key = jsonObject.getString("locationName");
					String value = jsonObject.getString("key");
	  
				    valueMap.put(key, value);
				  
			%>

			<option value="<%=value%>"><%=key%></option>

			<%
				}}
			%>
		

			</select>
			
		</td>
	</tr>
	</table>
</div>
<form   name= "editForm"   method= "post"   action= "editEvent.jsp"> 
<input   type= "hidden"   name= "id"> 
<input   type= "hidden"   name= "title"> 
<input   type= "hidden"   name= "description"> 
<input   type= "hidden"   name= "start"> 
<input   type= "hidden"   name= "end"> 
<input   type= "hidden"   name= "view">
<input   type= "hidden"   name= "locationKey"> 
<input   type= "hidden"   name= "locationName">
</form>
<select id="source">
        
        
    </select>
</body>
</html>